const { ipcRenderer } = require('electron');

let files = [];
let outputFolder = '';

// 拖放功能
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');

dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropZone.classList.add('dragover');
});

dropZone.addEventListener('dragleave', () => {
    dropZone.classList.remove('dragover');
});

dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropZone.classList.remove('dragover');
    handleFiles(e.dataTransfer.files);
});

fileInput.addEventListener('change', (e) => {
    handleFiles(e.target.files);
});

function handleFiles(newFiles) {
    Array.from(newFiles).forEach(file => {
        if (file.name.toLowerCase().endsWith('.ncm') && !files.find(f => f.path === file.path)) {
            files.push(file);
        }
    });
    updateFileList();
}

function updateFileList() {
    const fileList = document.getElementById('fileList');
    const convertBtn = document.getElementById('convertBtn');
    
    if (files.length === 0) {
        fileList.innerHTML = '';
        convertBtn.classList.add('hidden');
        return;
    }
    
    fileList.innerHTML = files.map((file, index) => `
        <div class="file-item">
            <div class="flex justify-between items-start">
                <div class="flex-1">
                    <h4 class="font-semibold text-gray-800">${file.name}</h4>
                    <p class="text-sm text-gray-600">${formatFileSize(file.size)}</p>
                </div>
                <button onclick="removeFile(${index})" 
                        class="btn btn-ghost btn-sm text-red-500">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="mt-3">
                <div class="progress-bar">
                    <div class="progress-fill" id="progress-${index}" style="width: 0%"></div>
                </div>
                <p class="text-sm text-gray-600 mt-1" id="status-${index}">等待转换...</p>
            </div>
        </div>
    `).join('');
    
    convertBtn.classList.remove('hidden');
}

function removeFile(index) {
    files.splice(index, 1);
    updateFileList();
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

async function selectOutputFolder() {
    const folder = await ipcRenderer.invoke('select-output-folder');
    if (folder) {
        outputFolder = folder;
        document.getElementById('outputFolder').value = folder;
    }
}

async function startConversion() {
    if (files.length === 0) {
        alert('请先添加NCM文件');
        return;
    }
    
    if (!outputFolder) {
        alert('请选择输出文件夹');
        return;
    }
    
    const convertBtn = document.getElementById('convertBtn');
    convertBtn.disabled = true;
    convertBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>转换中...';
    
    const format = document.getElementById('outputFormat').value;
    
    try {
        const results = await ipcRenderer.invoke('convert-files', files, format, outputFolder);
        showResults(results);
    } catch (error) {
        alert('转换失败: ' + error.message);
    } finally {
        convertBtn.disabled = false;
        convertBtn.innerHTML = '<i class="fas fa-play mr-2"></i>开始转换';
    }
}

// 监听转换进度
ipcRenderer.on('conversion-progress', (event, { file, progress }) => {
    const index = files.findIndex(f => f.path === file.path);
    if (index !== -1) {
        const progressBar = document.getElementById(`progress-${index}`);
        const statusText = document.getElementById(`status-${index}`);
        
        if (progressBar && statusText) {
            progressBar.style.width = `${progress}%`;
            statusText.textContent = progress === 100 ? '转换完成' : `转换中... ${progress}%`;
        }
    }
});

function showResults(results) {
    const modal = document.getElementById('resultModal');
    const content = document.getElementById('resultContent');
    
    const successCount = results.filter(r => r.success).length;
    const failCount = results.length - successCount;
    
    content.innerHTML = `
        <div class="space-y-4">
            <div class="stats stats-vertical w-full">
                <div class="stat">
                    <div class="stat-figure text-success">
                        <i class="fas fa-check-circle text-3xl"></i>
                    </div>
                    <div class="stat-title">成功</div>
                    <div class="stat-value text-success">${successCount}</div>
                </div>
                <div class="stat">
                    <div class="stat-figure text-error">
                        <i class="fas fa-exclamation-circle text-3xl"></i>
                    </div>
                    <div class="stat-title">失败</div>
                    <div class="stat-value text-error">${failCount}</div>
                </div>
            </div>
            
            ${results.filter(r => !r.success).map(r => `
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-triangle"></i>
                    <span>${path.basename(r.file.path)}: ${r.error}</span>
                </div>
            `).join('')}
        </div>
    `;
    
    modal.classList.add('modal-open');
}

function closeModal() {
    document.getElementById('resultModal').classList.remove('modal-open');
}

async function openOutputFolder() {
    if (outputFolder) {
        await ipcRenderer.invoke('open-folder', outputFolder);
    }
    closeModal();
}

// 默认输出文件夹
selectOutputFolder();
